package com.example.springbootflowabledemo.util;

import com.example.springbootflowabledemo.constant.ContextHolderConstants;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 上下文存储
 */
public class ContextHolderUtil {
    private static final ThreadLocal<Map<String, Object>> THREAD_LOCAL = new ThreadLocal<>();

    private static Map<String, Object> getLocalMap() {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (map == null) {
            map = new ConcurrentHashMap<String, Object>();
            THREAD_LOCAL.set(map);
        }
        return map;
    }


    /**
     * 往缓线程本地缓存中set值
     *
     * @param key
     * @param value
     */
    public static void set(String key, Object value) {
        Map<String, Object> map = getLocalMap();
        map.put(key, value == null ? StringUtils.EMPTY : value);
    }

    /**
     * 获取当前用户id
     *
     * @return
     */
    public static Long getUserId() {
        Map<String, Object> map = getLocalMap();
        Object userId = map.getOrDefault(ContextHolderConstants.USER_ID, 0L);
        return (Long) userId;
    }

//    /**
//     * 获取当前登录用户角色
//     *
//     * @return
//     */
//    public static String getUserRole() {
//        Map<String, Object> map = getLocalMap();
//        return (String) map.getOrDefault(ContextHolderConstants.ROLE, RoleConstants.EMP);
//    }
}
